package work.huangxin.share.config;

import cn.hutool.core.date.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * @author 季台星
 * @Date 2023 04 13 18 36
 * 定时清理上传商品接口中产生的临时文件
 */
@Component
@Slf4j
public class CleanUpImage {
//    @Value("${sechand.image.path}")
    public String path = "/opt/software/images/";

    /**
     * 每五个小时执行一次
     */
    @Scheduled(cron = "0 0 */5 * * *")
    public void CleanImage(){
      log.info("定时任务启动-----》" + DateTime.now());
      //判断路径是否为空
      if (Strings.isBlank(path)){
          log.error("请检查需要清理的图片路径");
          return;
      }
      File file = new File(path);
      if (!file.isDirectory()){
          log.error("路径不存在");
          return;
      }
      //如果路径存在删除路径下所有图片
        try {
            FileUtils.cleanDirectory(file);
            log.info("删除文件成功-------》" + DateTime.now());
        } catch (IOException e) {
            log.info("删除失败");
            throw new RuntimeException(e);
        }
    }
}
